package com.tourism.config.handler;

/**
 * @Description
 * @Author z
 * @Date 2021-03-04 20:53
 */

import com.tourism.entity.User;
import com.tourism.util.JwtTokenUtil;
import com.tourism.util.ServletUtils;
import com.tourism.util.SystemHelper;
import com.tourism.util.TokenManager;
import com.tourism.util.common.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 登陆成功处理handler
 */
@Component
public class LoginSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {


    @Autowired
    private JwtTokenUtil jwtTokenUtil;//生成token的工具类
    @Resource
    private TokenManager tokenManager;//token过期时间管理类

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {

        User currentUser = SystemHelper.getCurrentUser();
        //生成登录token
        String token = jwtTokenUtil.generateToken(currentUser);
        tokenManager.storeToken(token);
        Map<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        currentUser.setPassword(null);
        tokenMap.put("userId", currentUser.getId().toString());
        tokenMap.put("role", currentUser.getRole());
        ServletUtils.render(response, Response.success(tokenMap));

    }

}
